package dao.impl;

import dao.BaseDao;
import dao.OrderItemDao;
import domain.OrderItem;
import utils.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class OrderItemDaoImpl extends BaseDao implements OrderItemDao {
    @Override
    public int saveOrderItem(OrderItem orderItem) {
        Connection conn = null;
        int update = 0;
        try {
            conn = JDBCUtils.getDruidConnection();
            String sql = "insert into t_order_item(name,count,price,total_price,order_id) " +
                    "values(?,?,?,?,?);";
            update = update(conn, sql, orderItem.getName(), orderItem.getCount(), orderItem.getPrice(),
                    orderItem.getTotalPrice(), orderItem.getOrderId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return update;
    }

    @Override
    public List<OrderItem> queryOrderItemsByOrderId(String orderId) {
        Connection conn = null;
        List<OrderItem> orderItems = null;
        try {
            conn = JDBCUtils.getDruidConnection();
            String sql = "SELECT `id`,`name`,`count`,`price`,`total_price` AS `totalPrice`,`order_id` AS `orderId` from t_order_item WHERE `order_id` = ?;";
            orderItems = queryForMore(conn, sql, OrderItem.class, orderId);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtils.closeResource(conn,null);
        }
        return orderItems;
    }
}
